import 'package:dio/dio.dart';
import 'package:get/get.dart';
import 'package:wk_robot2/app/const/AppConst.dart';
import 'package:wk_robot2/app/event/DataCallBack.dart';
import 'package:wk_robot2/app/nets/NetWorkManager.dart';
import 'package:wk_robot2/app/storage/StorageManager.dart';
import 'package:wk_robot2/app/utils/CommonUtil.dart';

import '../../../robot_comm/mqtt_comm_manager.dart';
import '../../../routes/app_pages.dart';

class LauncherController extends GetxController {

  @override
  void onInit() {
    print('onInit ...');
    super.onInit();
    syncServerTime();
  }

  @override
  void onReady() {
    super.onReady();

    Future.delayed(Duration(seconds: 2),() {
        //同步服务器时间.
        syncServerTime();
        if (StorageManager.getStorage().hasData(AppConst.storage_key_login_token)) {
          int currentMillTime = DateTime.now().millisecondsSinceEpoch;
          int expiredAt = StorageManager.getStorage().read(AppConst.storage_key_login_token)['expireAt'];

          double pendingDay = (expiredAt - currentMillTime)/(60*1000*60*24);
          if(pendingDay < 2.00) {
            refreshToken();
          }

          // 跳转到首页
          Get.offNamed(Routes.HOME);
 
        } else {
          //跳转登录.
          Get.offNamed(Routes.LOGIN);
        }
    });

  }


  void  refreshToken() {
     Future.delayed(Duration(seconds: 2),() {
          NetWorkManager.getInstance().requestBussiness(NetWorkManager.TO_REFRESH_TOKEN, {
            'refreshToken': StorageManager.getStorage().read(AppConst.storage_key_login_token)['refreshToken']
          }, NetWorkManager.methodGET, DataCallBack(
             businessCallBack: (v) {
               StorageManager.getStorage().write(AppConst.storage_key_login_token,v);
             }
          ));


     });
  }

  void syncServerTime () async   {
    final response = await Dio().get('https://apis.ubtrobot.com/v1/client-auth-service/api/timestamp');
    if (!StorageManager.getStorage().hasData(AppConst.storage_server_system_timestamp)) {
      StorageManager.getStorage().write(AppConst.storage_server_system_timestamp, response.data['timestamp']);
      StorageManager.getStorage().write(AppConst.storage_local_system_timestamp, (DateTime.now().millisecondsSinceEpoch/1000).toInt());
    }
  }


}
